package com.weilive.api.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.weilive.core.utils.HttpUtils;

public final class BaiduMapUtil {

	private static final String AK = "UaBKvYdj4IYmtavXcxbXQcQe";

	private static final String REQUEST_URL = "http://api.map.baidu.com/geocoder/v2/?output=json&ak=" + AK + "&";

	public static final class Point {
		public String lat;// 维度
		public String lng;// 经度

		public Point(String lat, String lng) {
			this.lat = lat;
			this.lng = lng;
		}

		public String toString() {
			if (StringUtils.isBlank(lat) || StringUtils.isBlank(lng)) {
				return "";
			}
			return lat + "," + lng;
		}

		public static Point EmptyPoint() {
			return new Point(null, null);
		}
	}

	/**
	 * 通过经纬度获取地址
	 * 
	 * @param lat
	 * @param lng
	 * @return
	 */
	public static final String getAddress(Point point) {

		try {
			String getURL = REQUEST_URL + "location=" + point.toString() + "&pois=0";
			String result = HttpUtils.HttpGetGo(getURL);

			System.out.println(result);
			JSONObject json = JSONObject.parseObject(result);
			int status = json.getIntValue("status");
			if (status != 0) {
				return "";
			}
			return URLDecoder.decode(json.getJSONObject("result").getString("formatted_address"), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 通过地址获取经纬度
	 * 
	 * @param address
	 * @return
	 */
	public static final Point getPoint(String address, String city) {
		try {
			String getURL = REQUEST_URL + "address=" + URLEncoder.encode(address, "utf-8");

			if (!StringUtils.isBlank(city)) {
				getURL += "&city=" + URLEncoder.encode(city, "utf-8");
			}

			String result = HttpUtils.HttpGetGo(getURL);

			System.out.println(result);

			JSONObject json = JSONObject.parseObject(result);

			int status = json.getIntValue("status");
			if (status != 0) {
				return Point.EmptyPoint();
			}
			JSONObject obj = json.getJSONObject("result").getJSONObject("location");

			return new Point(obj.getString("lat"), obj.getString("lng"));

		} catch (Exception e) {
			e.printStackTrace();
		}
		return Point.EmptyPoint();
	}

	public static void main(String[] args) throws UnsupportedEncodingException {

		Point p = getPoint("东新路88弄22号", "上海市");

		System.out.println(p.toString());

		String add = getAddress(p);

		System.out.println(add);
	}
}
